package com.xywh.wanandroid.compose_ui.collect

import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.consumeWindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material.pullrefresh.PullRefreshIndicator
import androidx.compose.material.pullrefresh.pullRefresh
import androidx.compose.material.pullrefresh.rememberPullRefreshState
import androidx.compose.material3.Divider
import androidx.compose.material3.FabPosition
import androidx.compose.material3.Icon
import androidx.compose.material3.ListItem
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.paging.compose.LazyPagingItems
import androidx.paging.compose.collectAsLazyPagingItems
import com.xywh.composeLibrary.ext.ListFloatingActionButton
import com.xywh.composeLibrary.statex.PageState
import com.xywh.composeLibrary.statex.StateCompose
import com.xywh.composeLibrary.view.XxTopAppBarCenter
import com.xywh.wanandroid.data.model.bean.CollectArticlesData
import com.xywh.wanandroid.viewmodel.CollectComposeViewModel
import com.xywh.wanandroid.viewmodel.MainComposeViewModel
import me.hgj.jetpackmvvm.ext.util.loge

@Composable
fun CollectScreen(
    mainComposeViewModel: MainComposeViewModel,
    viewModel: CollectComposeViewModel = hiltViewModel(),
    navigateUp: () -> Unit,
    navigateWebView: (String, String) -> Unit
) {
//    val lifecycleOwner = (LocalContext.current as LifecycleOwner)

    val listState = rememberLazyListState()
    val refresh = remember { mutableStateOf(false) }

    XxTopAppBarCenter(
        title = "收藏",
        navigationIconOnClick = { navigateUp.invoke() },
        content = { innerPadding ->

            val contentState = remember {
                PageState(PageState.loading())
            }

            val collectList = viewModel.collectListLiveData.collectAsLazyPagingItems()

            StateCompose(collectList, contentState) {
                CollectContent(
                    refresh.value,
                    listState,
                    innerPadding,
                    collectList,
                    navigateWebView = navigateWebView
                ) { id, originId ->
                    viewModel.removeCollectArticle(id, originId) {
                        mainComposeViewModel.updateCollectArticleListData()
                        collectList.itemSnapshotList.items.size.toString().loge("itemSnapshotList=")
                        if (collectList.itemSnapshotList.items.size == 1) {
                            contentState.changeState(PageState.empty())
                        }
                    }
                }
            }

        },
        floatingActionButtonPosition = FabPosition.End,
        floatingActionButton = {
            ListFloatingActionButton(rememberCoroutineScope(), listState)
        })

}


@Composable
@OptIn(ExperimentalMaterialApi::class, ExperimentalFoundationApi::class)
fun CollectContent(
    refreshCancel: Boolean,
    listState: LazyListState,
    innerPadding: PaddingValues,
    collectList: LazyPagingItems<CollectArticlesData>,
    navigateWebView: (String, String) -> Unit,
    favoriteCancelOnClick: (Int, Int) -> Unit

) {


    val refresh by remember { mutableStateOf(false) }
    val pullRefreshState = rememberPullRefreshState(refresh, {
        collectList.refresh()
    })



    if (refreshCancel) {
        collectList.refresh()
    }
    Box(
        modifier = Modifier
            .fillMaxSize()
            .pullRefresh(pullRefreshState)
    ) {


        LazyColumn(
            state = listState,
            // consume insets as scaffold doesn't do it by default
            modifier = Modifier
                .consumeWindowInsets(innerPadding),
            contentPadding = innerPadding,
        ) {
            items(
                count = collectList.itemCount,
                key = { index ->
                    val collect = collectList[index]
                    "${collect?.id ?: ""}${index}"
                }) {
                collectList[it]

                val itemData = collectList[it] ?: return@items
                CollectItem(
                    itemData,
                    favoriteCancelOnClick = favoriteCancelOnClick
                ) { title, link ->
                    navigateWebView.invoke(title, link)
                }
            }

        }
        PullRefreshIndicator(
            refresh,
            pullRefreshState,
            Modifier.align(Alignment.TopCenter),
            scale = true
        )
    }
}

@Composable
fun CollectItem(
    collectArticlesData: CollectArticlesData,
    favoriteCancelOnClick: (Int, Int) -> Unit = { id, originId -> },
    itemOnClick: (title: String, link: String) -> Unit
) {
    ListItem(
        modifier = Modifier.clickable {
            itemOnClick.invoke(collectArticlesData.title, collectArticlesData.link)
        },
        headlineContent = {
            Text(
                collectArticlesData.title,
                fontSize = 14.sp,
                color = Color.Black,
                modifier = Modifier
                    .padding(top = 10.dp)
                    .fillMaxWidth(),
            )
        },
        overlineContent = {
            Row(Modifier.fillMaxWidth()) {

                Text(
                    collectArticlesData.author.ifEmpty { "匿名" },
                    fontSize = 10.sp,
                    color = Color(0xFF747474),
                    modifier = Modifier
                        .align(Alignment.Bottom)
                )

                Text(
                    //                                        "2023-11-10 15:33:48",
                    collectArticlesData.niceDate,
                    fontSize = 10.sp,
                    color = Color(0xFF747474),
                    modifier = Modifier
                        .padding(start = 5.dp)
                        .fillMaxWidth()
                        .align(Alignment.Bottom),
                    textAlign = TextAlign.End
                )
            }
        },
        supportingContent = {


            Row(
                Modifier
                    .padding(top = 10.dp)
                    .fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween
            ) {

                Text(
                    collectArticlesData.chapterName,
                    fontSize = 12.sp,
                    color = Color(0xFF787878)
                )

                val favorite = Icons.Filled.Favorite

                Icon(
                    favorite,
                    modifier = Modifier
                        .size(18.dp)
                        .clickable {
                            favoriteCancelOnClick.invoke(
                                collectArticlesData.id,
                                collectArticlesData.originId
                            )
                        },
                    contentDescription = "Localized description",
                )
            }
        },
        //                        leadingContent = {
        //
        //                        },
        //                        trailingContent = {
        //
        //                        }
    )
    Divider()
}
